package cn.mrcode.wxsdk.core.dialogue.common.accessToken;

import cn.mrcode.wxsdk.core.context.ConfigContext;
import cn.mrcode.wxsdk.core.dialogue.common.exception.ReqException;
import cn.mrcode.wxsdk.core.dialogue.common.exception.WxException;
import cn.mrcode.wxsdk.core.dialogue.common.util.DateUtil;
import cn.mrcode.wxsdk.core.dialogue.protocol.base.AccessTokenInfo;
import cn.mrcode.wxsdk.core.dialogue.service.BaseService;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.Date;



/**
 *  acaccessToken api 服务
 * @author zhuqiang
 * @version V1.0
 * @date 2015/9/22 17:06
 */
public class AccessTokenApi extends BaseService {
    private static Logger log = LoggerFactory.getLogger(AccessTokenApi.class);
    //获取accesstoken_url
    private static final String ACCESSTOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    /**
     * 获取 有时间控制的AccessTokenInfo，<br/>
     * 注意：该方法会直接去调用api 刷新token。一般不建议开发中使用该方法
     *
     * @param appid
     * @param secret
     *
     * @return
     */
    public static AccessTokenInfo getAccessTokenInfo(String appid, String secret) throws ReqException, WxException {
        return getAccessTokenInfo(appid,secret,null);
    }

    /**
     * 获取 有时间控制的AccessTokenInfo，<br/>
     * 注意：该方法会直接去调用api 刷新token。一般不建议开发中使用该方法
     * @param appid
     * @param secret
     * @param lastUpdateBy 最后一次更新者
     * @return
     * @throws ReqException
     * @throws WxException
     */
    public static AccessTokenInfo getAccessTokenInfo(String appid, String secret,String lastUpdateBy) throws ReqException, WxException {
        String accesstoken =  getBaseAccessToken(appid, secret);
        AccessTokenInfo result = new AccessTokenInfo();
        result.setAppID(appid);
        result.setAppSecret(secret);
        result.setAccessToken(accesstoken);
        result.setCreateTime(new Date());
        result.setTimeOut(DateUtil.computingTime(result.getCreateTime(), Calendar.MINUTE, ConfigContext.accesstokenTimeOut));
        result.setLastUpdateBy(lastUpdateBy);
        return result;
    }

    /**
     * 获取accesstoken
     *
     * @param appid  开发者账户
     * @param secret 密钥
     *
     * @throws
     */
    private static String getBaseAccessToken(String appid, String secret) throws ReqException, WxException {
        String jsonStr = get(ACCESSTOKEN_URL.concat("&appid=").concat(appid).concat("&secret=").concat(secret));
        JSONObject resultObj = JSONObject.parseObject(jsonStr);
        handerThrowErrcode(resultObj);
        return resultObj.getString("access_token");
    }
}
